package org.ytor.core.sqlflow.enums;

/**
 * created by yangtong on 2025/8/12 18:04:47
 * <br/>
 * SQL 类型
 */
public enum SqlType {
    INSERT, DELETE, UPDATE, SELECT;

    /**
     * 根据SQL字符串解析SQL类型
     */
    public static SqlType parseType(String sql) {
        if (sql == null) {
            throw new NullPointerException("解析SQL类型时遇到异常:待解析SQL字符串为空");
        }
        sql = sql.trim();
        if (sql.length() <= 6) {
            throw new IllegalArgumentException("未知类型SQL: " + sql);
        }

        sql = sql.substring(0, 6).toUpperCase();
        if (sql.startsWith("INSERT")) {
            return INSERT;
        } else if (sql.startsWith("DELETE")) {
            return DELETE;
        } else if (sql.startsWith("UPDATE")) {
            return UPDATE;
        } else if (sql.startsWith("SELECT")) {
            return SELECT;
        } else {
            throw new IllegalArgumentException("未知类型SQL: " + sql);
        }
    }

    /**
     * 根据SQL字符串解析主表名称
     */
    public static String parseTable(String sql) {
        if (sql == null) {
            return null;
        }
        String lower = sql.toUpperCase();
        sql = sql.trim();

        if (lower.startsWith("SELECT")) {
            return extractAfterKeyword(sql, " FROM ");
        }
        if (lower.startsWith("DELETE")) {
            if (lower.startsWith("DELETE FROM")) {
                return extractAfterKeyword(sql, " FROM ");
            } else {
                return extractAfterKeyword(sql, "DELETE ");
            }
        }
        if (lower.startsWith("UPDATE")) {
            return extractAfterKeyword(sql, "UPDATE ");
        }
        if (lower.startsWith("INSERT INTO")) {
            return extractAfterKeyword(sql, "INSERT INTO ");
        }
        if (lower.startsWith("INSERT")) {
            return extractAfterKeyword(sql, "INSERT ");
        }
        return null;
    }

    private static String extractAfterKeyword(String sql, String keyword) {
        int idx = sql.indexOf(keyword);
        if (idx == -1) return null;
        int start = idx + keyword.length();
        // 跳过空白
        while (start < sql.length() && Character.isWhitespace(sql.charAt(start))) {
            start++;
        }
        // 找到下一个空白
        int end = start;
        while (end < sql.length() && !Character.isWhitespace(sql.charAt(end))) {
            end++;
        }
        return sql.substring(start, end).trim();
    }
}
